<template>
  <view class="remark-form">
    <picker @change="invoiceTypeConfirm" @cancel="cancelInvoiceType" mode="selector" :range="invoiceTypeData"
      range-key="text">
      <cell label="发票类型" placeholder="请选择" :required="isRrequired" :value="getInvoiceTypeText || ''" />
    </picker>
    <cell label="发票抬头" placeholder="请输入开票信息" @click="checkisSelected('ghdwmc')" :required="isRrequired || isSelected"
      :value="invoice.ghdwmc" />
    <cell label="税号" :arrow="false" @click="checkisSelected" :required="isRrequired || isSelected"
      :cellContentHeight="cellContentHeight">
      <input class="amount-ipt" :disabled="!isSelected" placeholder="请输入纳税人识别号" placeholder-class="placeholder-class"
        v-model.trim="invoice.ghdwsbh" />
    </cell>
    <cell label="电子邮箱" @click="checkisSelected" :arrow="false" :required="isElectronic" v-if="isElectronic"
      :cellContentHeight="cellContentHeight">
      <input class="amount-ipt" :disabled="!isSelected" placeholder="用于获取电子发票" placeholder-class="placeholder-class"
        v-model.trim="invoice.spryx" />
    </cell>
    <cell :label="item.label" @click="checkisSelected" :arrow="false" :required="isSpecial" v-for="item in fieldLast"
      :key="item.key" v-if="isShow" :cellContentHeight="cellContentHeight">
      <input class="amount-ipt" :disabled="!isSelected" :placeholder="item.holder" placeholder-class="placeholder-class"
        v-model.trim="invoice[item.key]" />
    </cell>
    <cell label="发票备注" @click="checkisSelected" :arrow="false" :border="isGeneral" v-if="isShow"
      :cellContentHeight="cellContentHeight">
      <input class="amount-ipt" :disabled="!isSelected" placeholder="发票备注信息" placeholder-class="placeholder-class"
        v-model.trim="invoice.remark" maxlength="83" />
    </cell>
    <view class="flexbox" v-if="isGeneral">
      <view class="flexbox is-show" @click="isShow = !isShow">
        <text>发票详情</text>
        <image class="icon-img" :src="$getImg(`iassCashier/arrow-${isShow ?  'up':'down'}.png`)" mode="widthFix">
        </image>
      </view>
    </view>
    <uni-popup ref="ghdwmcpopup" type="right" :mask-click="false" :is-mask-click="false" @change="popupChange">
      <view class="popup-form">
        <view class="flexbox ">
          <view class="flexbox search-bar ">
            <input class="search-center" v-model.trim="invoice.ghdwmc" confirm-type="search" placeholder="请输入关键词"
              @confirm="search" @input="search" />
            <image :src="$getImg('iassCashier/search_3.png')" mode="scaleToFill" @click="search" class="search-img">
            </image>
          </view>
          <button class="confirm-btn popup-title" @click="closePopup">取消</button>
        </view>
        <scroll-view scroll-y="true" class="contaier-box">
          <cell v-for="item in dataList" :is-label="false" :key="item.nsrsbh" @click="selecteCompany(item)"
            :value="item.nsrmc" />
          <view style="padding-bottom: 20vh;"></view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import Cell from './Cell.vue';
  import {
    queryByTitle
  } from "../api/pay.js";
  import {
    debounce,
    isEmpty
  } from "@/common/util.js";
  export default {
    props: {
      // 是否强制开票，1-是 0-不是 2-不开票
      requiredFlag: {
        type: String,
        default: '1'
      },
      // 开票类型 参数类似于 "1,2,3,4"
      requiredInvoice: {
        type: String,
        default: "1,2,3,4"
      }
    },
    watch: {
      "invoice.fplxdm": {
        handler(newVal) {
          this.isShow = this.isSpecial
          if (!this.isElectronic) this.invoice.spryx = ''
        }
      }
    },
    components: {
      Cell
    },
    data() {
      return {
        cellContentHeight: '20px',
        invoice: {
          fplxdm: "", //发票类型
          ghdwmc: "", //发票抬头
          ghdwsbh: "", //发票税号
          spryx: "", //电子邮箱
          ghdwdzdh: "", //单位地址和电话
          ghdwyhzh: "", //单位银行账户
          remark: "", //开票备注
        },
        fieldLast: [{
          label: "地址和电话",
          holder: "单位地址和电话",
          key: "ghdwdzdh",
        }, {
          label: "开户行及账号",
          holder: "单位开户行及账号",
          key: "ghdwyhzh",
        }],
        //发票类型
        invoiceType: [{
          text: "纸质发票(普票)",
          val: '2'
        }, {
          text: '纸质发票(专票)',
          val: '3'
        }, {
          text: '电子发票(普票)',
          val: '1'
        }, {
          text: '电子发票(专票)',
          val: '4'
        }, {
          text: '数电电子发票(普票)',
          val: '6'
        }, {
          text: '数电电子发票(专票)',
          val: '5'
        }],
        // 发票类型选择器显示隐藏
        showInvoiceTypePicker: false,
        // 发票抬头联想
        showInvoiceTitlePicker: false,
        // 发票抬头联想查询的数据
        dataList: [],
        isShow: false, // 最后两项显示
        //搜索抽屉组件的宽高
        searchPopup: {},
        // 单位时间段内 只能发一次请求
        isSearching: false,
        timerDebounceFn: null
      };
    },
    computed: {
      //是否强制开票
      isRrequired() {
        return this.requiredFlag == '1'
      },
      // 是否选择发票类型
      isSelected() {
        return !isEmpty(this.invoice.fplxdm)
      },
      // 是否专票
      isSpecial() {
        return ["3", "4", "5"].includes(this.invoice.fplxdm)
      },
      // 是否普票或者默认空值
      isGeneral() {
        return ["1", "2", "6", ""].includes(this.invoice.fplxdm)
      },
      // 是否电子发票
      isElectronic() {
        return ["1", "4", "5", "6"].includes(this.invoice.fplxdm)
      },
      // 验证邮箱
      emailIsTrue() {
        let pattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
        return pattern.test(this.invoice.spryx)
      },

      getInvoiceTypeText() {
        let val = this.invoice.fplxdm
        let item = this.invoiceType.find(item => item.val == val)
        return isEmpty(item) ? '' : item.text
      },
      // 开通的发票类型
      invoiceTypeData() {
        let data = [],
          str = this.requiredInvoice;
        this.invoiceType.forEach(item => {
          if (str.indexOf(item.val) >= 0 && !isEmpty(str)) {
            data.push(item)
          }
        })
        return data
      },
    },
    created() {
      this.timerDebounceFn = debounce(() => {
        this.getDataList()
      })
    },
    methods: {
      checkisSelected(f) {
        if (!this.isSelected) {
          this.$toast('请选择发票类型')
        } else {
          if (f === 'ghdwmc') this.openPopup()
        }
      },
      invoiceTypeConfirm(e) {
        let index = parseInt(e.detail.value)
        let item = this.invoiceTypeData[index]
        this.invoice.fplxdm = item.val
      },
      cancelInvoiceType() {
        if (!this.isRrequired) {
          Object.keys(this.invoice).forEach(key => {
            this.invoice[key] = ''
          })
          this.dataList = []
        }
      },
      requiredKeys(val) {
        // 发票抬头+税号
        let keyArr = [{
          key: "ghdwmc",
          tip: "请输入开票信息"
        }, {
          key: "ghdwsbh",
          tip: "请输入纳税人识别号"
        }];
        // 邮箱格式
        let keyArr2 = [{
          key: "spryx",
          tip: "请输入正确的邮箱格式"
        }];
        // 地址+账号
        let keyArr3 = [{
          key: "ghdwdzdh",
          tip: "请输入地址和电话"
        }, {
          key: "ghdwyhzh",
          tip: "请输入开户行及账号"
        }];
        switch (val) {
          case "2":
            return keyArr
          case "3":
            return [...keyArr, ...keyArr3]
          case "4":
          case "5":
            return [...keyArr, ...keyArr2, ...keyArr3]
          default:
            return [...keyArr, ...keyArr2]
        }
      },
      // 验证表单
      validateForm() {
        let flag = true
        // 强制开票必选发票类型
        if (this.isRrequired && !this.isSelected) {
          this.$toast('请选择发票类型')
          flag = false
        }
        // 无论是否强制开票，只要选择了开票类型，就要校验对应的必填项
        if (this.isSelected) {
          let arr = this.requiredKeys(this.invoice.fplxdm)
          for (let i = 0, length = arr.length; i < length; i++) {
            let item = arr[i]
            flag = item.key == "spryx" ? this.emailIsTrue : !isEmpty(this.invoice[item.key])
            if (!flag) {
              this.$toast(item.tip)
              break
            }
          }
        }
        return flag ? this.invoice : flag
      },
      openPopup(e) {
        this.$refs.ghdwmcpopup.open()
      },
      closePopup() {
        this.$refs.ghdwmcpopup.close()
      },
      popupChange(e) {
        this.$emit('popupChange', e)
      },
      selecteCompany(item) {
        this.invoice.ghdwmc = item.nsrmc
        this.invoice.ghdwyhzh = item.yhzh
        this.invoice.ghdwsbh = item.nsrsbh
        this.invoice.ghdwdzdh = item.dzdh
        this.closePopup()
      },
      async getDataList() {
        try {
          let val = isEmpty(this.invoice.ghdwmc) ? '' : this.invoice.ghdwmc.trim();
          this.invoice.ghdwmc = val;
          this.dataList = [];
          if (!isEmpty(val)) {
            let data = {
              title: this.invoice.ghdwmc
            }
            let res = await queryByTitle(data)
            if (res.length === 1) {
              let firstItem = res[0];
              if (isEmpty(firstItem.nsrmc)) firstItem.nsrmc = this.invoice.ghdwmc
            }
            this.dataList = res
          }
        } catch (e) {
          this.$toast(e.respMsg)
        }
      },
      search() {
        this.timerDebounceFn()
      },
      confirmRemark() {
        this.closePopup()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .remark-form {
    .flexbox {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }

    .is-show {
      font-size: 13px;
      color: #969799;
      padding: 6px 10px;

      .icon-img {
        display: block;
        width: 14px;
        height: 14px;
      }
    }

  }

  .popup-form {
    background-color: #fff;
    width: 100vw;
    height: 100vh;

    .contaier-box {
      height: calc(100vh - 52px);
    }

    .flexbox {
      border-bottom: 1rpx solid #ebedf0;
      padding: 8px 0 8px 10px;
    }

    .search-bar {
      flex: 1;
      background-color: #f6f7f8;
      padding: 5px 10px;
      border-radius: 5px;
      border: none;

      .search-center {
        flex: 1;
        height: 22px;
        padding-right: 10px;
        font-size: 14px;
      }

      .search-img {
        width: 16px;
        height: 16px;
      }
    }

    .confirm-btn {
      background-color: #fff;
      font-size: 15px;
      padding: 0 10px;
      height: 22px;
      line-height: 22px;
    }
  }

  .amount-ipt {
    height: 20px;
    line-height: 20px;
    font-size: 14px;
    width: 100%;
  }

  .placeholder-class {
    font-size: 14px;
    color: #969799;
  }

  .font-s {
    font-size: 14px;
    line-height: 20px;
    color: #333;
    word-break: break-all;
  }
</style>